<template>
  <div class="nfc-customer-pages">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>顾客端页面管理</h2>
      <p>管理所有NFC顾客端活动页面，查看访问统计和页面状态</p>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form
        :model="searchForm"
        :inline="true"
        class="search-form"
        @submit.native.prevent="handleSearch"
      >
        <el-form-item label="商户名称">
          <el-select
            v-model="searchForm.merchant_id"
            placeholder="请选择商户"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="merchant in merchantList"
              :key="merchant.id"
              :label="merchant.merchant_name"
              :value="merchant.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="页面状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">
            重置
          </el-button>
          <el-button 
            type="success" 
            icon="el-icon-download" 
            @click="handleExport"
            :loading="exportLoading"
          >
            导出数据
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="merchant.merchant_name" label="商户名称" min-width="120" />
        <el-table-column prop="campaign_name" label="活动名称" min-width="150" />
        <el-table-column label="页面地址" min-width="200">
          <template slot-scope="scope">
            <el-link 
              :href="scope.row.page_url" 
              target="_blank" 
              type="primary"
              style="word-break: break-all"
            >
              {{ scope.row.page_url }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="访问统计" min-width="120">
          <template slot-scope="scope">
            <div class="stats-info">
              <div>访问: {{ scope.row.visit_count }}</div>
              <div>奖励: {{ scope.row.reward_count }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="最后访问" min-width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.last_visit_time">
              {{ formatTime(scope.row.last_visit_time) }}
            </span>
            <span v-else class="text-muted">无访问</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="120">
          <template slot-scope="scope">
            {{ formatTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="success"
              size="mini"
              icon="el-icon-monitor"
              @click="handlePreview(scope.row)"
            >
              预览
            </el-button>
            <el-button
              type="info"
              size="mini"
              icon="el-icon-data-line"
              @click="handleAnalytics(scope.row)"
            >
              统计
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 页面详情对话框 -->
    <el-dialog
      title="页面详情"
      :visible.sync="detailDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentItem" class="page-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>商户名称:</label>
              <span>{{ currentItem.merchant.merchant_name }}</span>
            </div>
            <div class="detail-item">
              <label>活动名称:</label>
              <span>{{ currentItem.campaign_name }}</span>
            </div>
            <div class="detail-item">
              <label>页面地址:</label>
              <el-link :href="currentItem.page_url" target="_blank" type="primary">
                {{ currentItem.page_url }}
              </el-link>
            </div>
            <div class="detail-item">
              <label>页面状态:</label>
              <el-tag :type="currentItem.status === 1 ? 'success' : 'danger'">
                {{ currentItem.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>访问统计:</label>
              <div class="stats-detail">
                <div>总访问量: {{ currentItem.visit_count }}</div>
                <div>奖励生成: {{ currentItem.reward_count }}</div>
                <div>转化率: {{ getConversionRate(currentItem) }}%</div>
              </div>
            </div>
            <div class="detail-item">
              <label>创建时间:</label>
              <span>{{ formatTime(currentItem.create_time) }}</span>
            </div>
            <div class="detail-item">
              <label>最后访问:</label>
              <span>{{ currentItem.last_visit_time ? formatTime(currentItem.last_visit_time) : '无访问' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <!-- 访问统计图表 -->
        <div v-if="currentItem.visit_stats" class="stats-chart">
          <h4>近7天访问统计</h4>
          <el-row :gutter="20">
            <el-col :span="8" v-for="stat in currentItem.visit_stats.recent_stats" :key="stat.date">
              <div class="stat-item">
                <div class="stat-date">{{ stat.date }}</div>
                <div class="stat-count">{{ stat.count }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePreview(currentItem)">预览页面</el-button>
      </div>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      title="页面预览"
      :visible.sync="previewDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <div v-if="previewData" class="preview-content">
        <div class="preview-info">
          <p><strong>商户:</strong> {{ previewData.merchant_name }}</p>
          <p><strong>活动:</strong> {{ previewData.campaign_name }}</p>
          <p><strong>预览地址:</strong></p>
          <el-link :href="previewData.preview_url" target="_blank" type="primary">
            {{ previewData.preview_url }}
          </el-link>
        </div>
        <div class="qr-code-container">
          <p><strong>二维码:</strong></p>
          <img :src="previewData.qr_code" alt="页面二维码" class="qr-code" />
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="openPreviewPage">打开页面</el-button>
      </div>
    </el-dialog>

    <!-- 统计分析对话框 -->
    <analytics-dialog
      :visible.sync="analyticsDialogVisible"
      :merchant-id="currentMerchantId"
      @close="analyticsDialogVisible = false"
    />
  </div>
</template>

<script>
import { getCustomerPageList, getCustomerPageInfo, previewCustomerPage, updateCustomerPageStatus, exportCustomerPageData } from '@/api/nfc-customer-pages'
import { getMerchantList } from '@/api/nfc'
import AnalyticsDialog from './components/AnalyticsDialog'

export default {
  name: 'NfcCustomerPages',
  components: {
    AnalyticsDialog
  },
  data() {
    return {
      loading: false,
      exportLoading: false,
      tableData: [],
      merchantList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchForm: {
        merchant_id: '',
        status: ''
      },
      detailDialogVisible: false,
      previewDialogVisible: false,
      analyticsDialogVisible: false,
      currentItem: null,
      previewData: null,
      currentMerchantId: null
    }
  },
  created() {
    this.loadMerchantList()
    this.loadTableData()
  },
  methods: {
    // 加载商户列表
    async loadMerchantList() {
      try {
        const res = await getMerchantList()
        if (res.code === 200) {
          // 根据API返回格式调整：res.data直接是数组
          this.merchantList = Array.isArray(res.data) ? res.data : (res.data.list || [])
        }
      } catch (error) {
        console.error('加载商户列表失败:', error)
      }
    },
    
    // 加载表格数据
    async loadTableData() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          limit: this.pageSize,
          ...this.searchForm
        }
        const res = await getCustomerPageList(params)
        if (res.code === 200) {
          this.tableData = res.data.list || []
          this.total = res.data.total || 0
        } else {
          this.$message.error(res.message || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadTableData()
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        merchant_id: '',
        status: ''
      }
      this.currentPage = 1
      this.loadTableData()
    },
    
    // 查看详情
    async handleView(row) {
      try {
        const res = await getCustomerPageInfo({ id: row.id })
        if (res.code === 200) {
          this.currentItem = res.data
          this.detailDialogVisible = true
        } else {
          this.$message.error(res.message || '获取详情失败')
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
      }
    },
    
    // 预览页面
    async handlePreview(row) {
      try {
        const res = await previewCustomerPage({ id: row.id })
        if (res.code === 200) {
          this.previewData = res.data
          this.previewDialogVisible = true
        } else {
          this.$message.error(res.message || '预览失败')
        }
      } catch (error) {
        console.error('预览失败:', error)
        this.$message.error('预览失败')
      }
    },
    
    // 打开预览页面
    openPreviewPage() {
      if (this.previewData && this.previewData.preview_url) {
        window.open(this.previewData.preview_url, '_blank')
      }
    },
    
    // 查看统计
    handleAnalytics(row) {
      this.currentMerchantId = row.merchant_id
      this.analyticsDialogVisible = true
    },
    
    // 状态变更
    async handleStatusChange(row) {
      try {
        const res = await updateCustomerPageStatus({
          id: row.id,
          status: row.status
        })
        if (res.code === 200) {
          this.$message.success(res.message || '状态更新成功')
          this.loadTableData()
        } else {
          this.$message.error(res.message || '状态更新失败')
          // 恢复原状态
          row.status = row.status === 1 ? 0 : 1
        }
      } catch (error) {
        console.error('状态更新失败:', error)
        this.$message.error('状态更新失败')
        // 恢复原状态
        row.status = row.status === 1 ? 0 : 1
      }
    },
    
    // 导出数据
    async handleExport() {
      this.exportLoading = true
      try {
        const res = await exportCustomerPageData(this.searchForm)
        if (res.code === 200) {
          this.downloadExcel(res.data)
          this.$message.success('导出成功')
        } else {
          this.$message.error(res.message || '导出失败')
        }
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      } finally {
        this.exportLoading = false
      }
    },
    
    // 下载Excel
    downloadExcel(data) {
      const csvContent = this.convertToCSV(data)
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `顾客端页面数据_${new Date().toISOString().slice(0, 10)}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    
    // 转换为CSV
    convertToCSV(data) {
      const headers = ['商户名称', '活动名称', '页面地址', '状态', '访问次数', '奖励次数', '最后访问时间', '创建时间']
      const rows = data.map(item => [
        item.merchant_name,
        item.campaign_name,
        item.page_url,
        item.status,
        item.visit_count,
        item.reward_count,
        item.last_visit_time,
        item.create_time
      ])
      
      return [headers, ...rows].map(row => row.join(',')).join('\n')
    },
    
    // 分页
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadTableData()
    },
    
    handleCurrentChange(page) {
      this.currentPage = page
      this.loadTableData()
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return new Date(time).toLocaleString()
    },
    
    // 计算转化率
    getConversionRate(item) {
      if (!item.visit_count || item.visit_count === 0) return 0
      return Math.round((item.reward_count / item.visit_count) * 100)
    }
  }
}
</script>

<style scoped>
.nfc-customer-pages {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-info {
  font-size: 12px;
  line-height: 1.5;
}

.text-muted {
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.page-detail {
  margin-bottom: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: bold;
  min-width: 80px;
  margin-right: 10px;
}

.stats-detail {
  font-size: 14px;
  line-height: 1.6;
}

.stats-chart {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.stat-item {
  text-align: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.stat-date {
  font-size: 12px;
  color: #909399;
}

.stat-count {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.preview-content {
  text-align: center;
}

.preview-info {
  margin-bottom: 20px;
  text-align: left;
}

.qr-code-container {
  text-align: center;
}

.qr-code {
  width: 150px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>